<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-select v-model="value" :placeholder="$t('message.select')">
            <el-option
              v-for="item in coinType"
              :key="item.symbol"
              :label="item.symbol"
              :value="item.symbol">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="commitData">{{$t('订阅')}}</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table
      :data="cData"
      :cell-style="rowStyle"
      :header-cell-style="rStyle"
      border
      style="width: 100%">
      <el-table-column
        fixed
        prop="symbol"
        :label="$t('message.pair-name')"
        width="150">
      </el-table-column>
      <el-table-column
        prop="bids_amount_sum"
        label="买方总量">
        <template slot-scope="scope">
          <span :class="scope.row.c1" style="font-weight: bold">{{scope.row.bids_amount_sum}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="asks_amount_sum"
        label="卖方总量">
        <template slot-scope="scope">
          <span :class="scope.row.c2" style="font-weight: bold">{{scope.row.asks_amount_sum}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="average_bid_price"
        label="买方均价">
        <template slot-scope="scope">
          <span :class="scope.row.c3" style="font-weight: bold">{{scope.row.average_bid_price}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="average_ask_price"
        label="卖方均价">
        <template slot-scope="scope">
          <span :class="scope.row.c4" style="font-weight: bold">{{scope.row.average_ask_price}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="bids_fund_sum"
        label="买方总额">
        <template slot-scope="scope">
          <span :class="scope.row.c5" style="font-weight: bold">{{scope.row.bids_fund_sum}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="asks_fund_sum"
        label="卖方总额">
        <template slot-scope="scope">
          <span :class="scope.row.c6" style="font-weight: bold">{{scope.row.asks_fund_sum}}</span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作">
        <template slot-scope="scope">
          <el-button @click="canselSub(scope.row.symbol)" type="text" size="small">取消订阅</el-button>
        </template>
      </el-table-column>
    </el-table>
  </section>
</template>

<script>
import { addedSymbolList, CancelSub } from '../api/api'
import url from 'common/js/http'
export default {
  name: 'socket',
  data () {
    return {
      coinType: [],
      value: '',
      initSendParam: {
        user_name: localStorage.getItem('user'),
        symbol: 'ETH_CNT'
      },
      data: null,
      cData: null,
      websock: null,
      reconnectData: null,
      lockReconnect: false,
      timeout: 10000,
      timeoutObj: null,
      serverTimeoutObj: null
    }
  },
  created () {
    addedSymbolList().then((res) => {
      if (res.data.code && res.data.code !== 0) {
        this.$message.error(this.$t('message.tip-33'))
      }
      this.coinType = res.data.symbols
    }).catch((res) => {
      console.log(res)
    })
    this.initWebSocket()
  },
  mounted () {
    console.log(222)
  },
  beforeDestroy () {
    console.log('断开链接')
    this.lockReconnect = true
    this.websock.close()
    clearTimeout(this.reconnectData)
    clearTimeout(this.timeoutObj)
    clearTimeout(this.serverTimeoutObj)
  },
  methods: {
    initWebSocket () { // 初始化weosocket
      const wsuri = `ws://${url.split('//')[1]}/userOrderInfo`
      this.websock = new WebSocket(wsuri)
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    websocketonopen () { // 连接建立之后执行send方法发送数据
      this.websocketsend(JSON.stringify(this.initSendParam))
      // this.heatBeat()
    },
    websocketonerror () { // 连接建立失败重连
      setTimeout(() => {
        this.initWebSocket()
      }, 2000)
    },
    websocketonmessage (e) {
      this.data = JSON.parse(e.data)
    },
    websocketsend (Data) { // 数据发送
      this.websock.send(Data)
    },
    websocketclose (e) { // 关闭
      console.log('断开连接', e)
      this.reconnect()
    },
    commitData () {
      this.value === '' ? this.$message.error('请选择交易对') : this.websocketsend(JSON.stringify(this.value))
    },
    reconnect () {
      if (this.lockReconnect) { // 这里很关键，因为连接失败之后之后会相继触发 连接关闭，不然会连接上两个 WebSocket
        return
      }
      this.lockReconnect = true
      this.reconnectData && clearTimeout(this.reconnectData)
      this.reconnectData = setTimeout(() => {
        this.initWebSocket()
        this.lockReconnect = false
      }, 5000)
    }, // socket重连
    // heatBeat () {
    //   this.timeoutObj && clearTimeout(this.timeoutObj)
    //   this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
    //   this.timeoutObj = setTimeout(() => {
    //     this.websocketsend(JSON.stringify(this.initSendParam)) // 根据后台要求发送
    //     this.serverTimeoutObj = setTimeout(() => {
    //       this.websock.close() // 如果  5秒之后我们没有收到 后台返回的心跳检测数据 断开socket，断开后会启动重连机制
    //     }, 10000)
    //   }, this.timeout)
    // },
    canselSub (symbol) {
      CancelSub({symbol: symbol}).then((res) => {
        if (res.data.code === 0) {
          this.$message.success('操作成功')
        } else {
          this.$message.error('操作失败')
        }
      }).catch(() => {
        this.$message.error('操作失败')
      })
    },
    rowStyle () {
      return {
        textAlign: 'center',
        padding: '0'
      }
    },
    rStyle () {
      return {
        textAlign: 'center'
      }
    }
  },
  watch: {
    data: {
      handler (newV, oldV) {
        if (!oldV || newV.length < 1) {
        } else {
          let arr = []
          for (let i = 0; i < newV.length; i++) {
            let obj = newV[i]
            obj.c1 = newV[i].bids_amount_sum > oldV[i].bids_amount_sum ? 'green' : (newV[i].bids_amount_sum < oldV[i].bids_amount_sum ? 'red' : '')
            obj.c2 = newV[i].asks_amount_sum > oldV[i].asks_amount_sum ? 'green' : (newV[i].asks_amount_sum < oldV[i].asks_amount_sum ? 'red' : '')
            obj.c3 = newV[i].average_bid_price > oldV[i].average_bid_price ? 'green' : (newV[i].average_bid_price < oldV[i].average_bid_price ? 'red' : '')
            obj.c4 = newV[i].average_ask_price > oldV[i].average_ask_price ? 'green' : (newV[i].average_ask_price < oldV[i].average_ask_price ? 'red' : '')
            obj.c5 = newV[i].bids_fund_sum > oldV[i].bids_fund_sum ? 'green' : (newV[i].bids_fund_sum < oldV[i].bids_fund_sum ? 'red' : '')
            obj.c5 = newV[i].asks_fund_sum > oldV[i].asks_fund_sum ? 'green' : (newV[i].bids_fund_sum < oldV[i].bids_fund_sum ? 'red' : '')
            arr.push(obj)
          }
          this.cData = arr
        }
      }
    },
    immediate: true
  }
}
</script>

<style scoped lang="scss">
.green {
  color: limegreen;
}
.red {
  color: red;
}
</style>
